package com.jt.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ContentMapper;
import com.jt.pojo.Content;
import com.jt.service.ContentService;
import com.jt.utils.Assert;
import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * @author dc
 * @Classname ContenServiceImpl
 * @Date 2020/3/24 12:04
 */
@Service
public class ContenServiceImpl implements ContentService {

    @Autowired
    private ContentMapper contentMapper;

    @Override
    public EasyUITable getContentByCategoryId(Integer page, Integer rows, Long categoryId) {
        //参数校验
        Assert.isValid(categoryId<0,"请先选择查看的节点!");
        //查询(MP实现)
        IPage<Content> iPage=new Page<>(page,rows);
        QueryWrapper<Content> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id",categoryId);
        IPage<Content> resultPage = contentMapper.selectPage(iPage, queryWrapper);
        List<Content> records = resultPage.getRecords();
        int total =(int)resultPage.getTotal();
        EasyUITable rs = new EasyUITable(total,records);
        return rs;
    }

    @Override
    public void saveContent(Content content) {
        //参数校验
        Assert.isValid(ObjectUtils.isEmpty(content),"请先填写内容!");
        //存储内容信息
        content.setCreated(new Date()).setUpdated(content.getCreated());
        int row = contentMapper.insert(content);
        Assert.isServiceValid(row==0,"网络繁忙,请稍后再试!");
    }

    @Override
    public void deleteConByIds(Long[] ids) {
        //参数校验
        Assert.isValid(ids.length<0,"请先选择要删除的内容!");
        //删除数据
        for(Long id:ids){
            int row = contentMapper.deleteById(id);
            Assert.isServiceValid(row==0,"网络繁忙,删除编号为"+id+"的内容失败!");
        }
    }

    @Override
    public void updateContent(Content content) {
        //参数校验
        Assert.isValid(ObjectUtils.isEmpty(content),"修改信息不能为空!");
        //修改数据
        content.setUpdated(new Date());
        int row = contentMapper.updateById(content);
        Assert.isServiceValid(row==0,"网络繁忙,请稍后再次修改!");
    }

    @Override
    public List<Content> findContentByCatId(Long categoryId) {
        //参数校验
        Assert.isValid(categoryId<0,"内容分类id出错!");
        QueryWrapper<Content> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",categoryId);
        List<Content> rs = contentMapper.selectList(wrapper);
        Assert.isServiceValid(rs.size()==0,"网络繁忙,稍后再试");
        return rs;
    }
}
